﻿using System;
using System.ComponentModel;


public static class YJUtilityConvertor
{
    public static T ConvertTo<T>(this object value)
    {
        if (value == null)
            return default(T);

        var destinationType = typeof(T);
        var sourceType = value.GetType();
        if (destinationType == typeof(bool) || destinationType == typeof(bool?))
            value = Convert.ToBoolean(value);

        TypeConverter destinationConverter = TypeDescriptor.GetConverter(destinationType);
        TypeConverter sourceConverter = TypeDescriptor.GetConverter(sourceType);
        if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
            return (T)destinationConverter.ConvertFrom(value);
        if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
            return (T)sourceConverter.ConvertTo(value, destinationType);
        if (destinationType.IsEnum && value is int)
            return (T)Enum.ToObject(destinationType, (int)value);
        if (!destinationType.IsInstanceOfType(value))
            return (T)Convert.ChangeType(value, destinationType);
        return (T)value;
    }

    public static bool Is<T>(this object value) where T : struct
    {
        if (value is T)
            return true;

        var destinationType = typeof(T);
        var sourceType = value.GetType();

        TypeConverter destinationConverter = TypeDescriptor.GetConverter(destinationType);
        TypeConverter sourceConverter = TypeDescriptor.GetConverter(sourceType);

        return destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType());
    }

}